package com.example.pdfandword.job;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.mime.MultipartEntity;
import org.apache.http.entity.mime.content.FileBody;
import org.apache.http.entity.mime.content.StringBody;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.annotation.SchedulingConfigurer;
import org.springframework.scheduling.config.ScheduledTaskRegistrar;
import org.springframework.scheduling.support.CronTrigger;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;

/**
 * @Package
 * @date 2021/4/16 10:17
 * @description
 */
@EnableScheduling
//@Configuration
@Slf4j
public class FileCollectionJob implements SchedulingConfigurer {

    @Value("${fileCollection.machineType}")
    private String machineType;
    @Value("${fileCollection.basedir}")
    private String basedir;
    @Value("${fileCollection.line}")
    private String line;
    @Value("${fileCollection.host}")
    private String uploadMachineFileHost;
    @Value("${fileCollection.corn}")
    private String corn;


    private static final String tbjFileDir = "MachineMonitoring";

    /**
     * 读取spi和贴片机文件
     * 每隔5分钟上传过去5分钟产生的文件
     */
    @Override
    public void configureTasks(ScheduledTaskRegistrar scheduledTaskRegistrar) {
        scheduledTaskRegistrar.addTriggerTask(() -> {
            log.info("扫描机器文件上传,当前机器类型:{}",machineType);
            File basedirs = new File(basedir);
            File[] dirs = basedirs.listFiles();
            if (dirs == null || dirs.length == 0) {
                return;
            }
            switch (machineType) {
                //每台一个txt文件
                case "spi":
                    List<File> spiCollectionFileList = new LinkedList<>();
                    for (File file : dirs) {
                        if (file.isDirectory()) {
                            continue;
                        }
                        if (".txt".equals(file.getName().substring(file.getName().lastIndexOf(".")))) {
                            spiCollectionFileList.add(file);
                        }
                    }
                    if (spiCollectionFileList.size() > 0) {
                        if (spiCollectionFileList.size() > 20) {
                            List<List<File>> groupList = groupList(30,spiCollectionFileList);
                            groupList.forEach(item -> {
                                sendFilesPost(uploadMachineFileHost+"/produce/fileCollection/receiveSpiFile",item,line);
                            });
                        }else {
                            sendFilesPost(uploadMachineFileHost+"/produce/fileCollection/receiveSpiFile",spiCollectionFileList,line);
                        }
                    }
                    break;
                //贴片机
                case "tpj":
                    Map<String,List<File>> fileMap = new HashMap<>();
                    for (File dir : dirs) {//每条机器目录
                        if (dir.isFile()) {
                            continue;
                        }
                        File[] dirList = dir.listFiles();
                        String line = dir.getName().split("-")[0];
                        if (dirList == null || dirList.length == 0) {
                            continue;
                        }
                        for (int i = 0; i < dirList.length; i++) {
                            File machineDir = dirList[i];
                            List<File> lineFileList = new ArrayList<>();
                            if (machineDir.isFile()) {
                                continue;
                            }
                            if (tbjFileDir.equals(machineDir.getName())) { //进入一台贴片机文件目录
                                File[] files = machineDir.listFiles();
                                if (files == null || files.length == 0) {
                                    continue;
                                }
                                for (File file : files) {
                                    //筛选需要上传的文件
                                    if (file.isDirectory()) {
                                        continue;
                                    }
                                    if ("TotalProduction.xml".equals(file.getName().substring(file.getName().lastIndexOf("_")+1))) {
                                        lineFileList.add(file);
                                    }
                                }
                            }
                            if (fileMap.get(line) !=null) {
                                fileMap.get(line).addAll(lineFileList);
                            }else {
                                fileMap.put(line,lineFileList);
                            }
                        }
                    }
                    //上传文件
                    if (fileMap.size() > 0) {
                        for (String machineLine : fileMap.keySet()) {
                            List<File> fileList = fileMap.get(machineLine);
                            if (fileList.size() > 10) {
                                List<List<File>> groupList = groupList(10,fileList);
                                groupList.forEach(item -> {
                                    sendFilesPost(uploadMachineFileHost+"/produce/fileCollection/receiveTpjFile",item,machineLine);
                                });
                            }else if (fileList.size() > 0){
                                sendFilesPost(uploadMachineFileHost+"/produce/fileCollection/receiveTpjFile",fileList,machineLine);
                            }
                        }
                    }
                    break;
                case "aoi":
                    List<File> fileList = new ArrayList<>();
                    for (int i = 0; i < dirs.length; i++) {
                        File dir = dirs[i];
                        if ("EXCEL".equals(dir.getName().toUpperCase())) { //进入Excel目录
                            File[] dateDirs = dir.listFiles();
                            if (dateDirs == null || dateDirs.length == 0) {
                                return;
                            }
                            for (int j = 0; j < dateDirs.length; j++) {//进入日期目录
                                File dateDir = dateDirs[j];
                                if (dateDir.isFile()) {
                                    continue;
                                }
                                File[] files = dateDir.listFiles();
                                if (files == null || files.length == 0) {
                                    continue;
                                }
                                for (int k = 0; k < files.length; k++) {
                                    File file = files[k];
                                    if (file.isFile() && ".xls".equals(file.getName().substring(file.getName().lastIndexOf(".")))) {
                                        fileList.add(file);
                                    }
                                }
                            }
                        }
                    }
                    //上传文件
                    if (fileList.size() > 0) {
                        if (fileList.size() > 10) {
                            List<List<File>> groupList = groupList(10,fileList);
                            groupList.forEach(item -> {
                                sendFilesPost(uploadMachineFileHost+"/produce/fileCollection/receiveAoiFile",item,line);
                            });
                        }else {
                            sendFilesPost(uploadMachineFileHost+"/produce/fileCollection/receiveAoiFile",fileList,line);
                        }
                    }
                    break;
            }
        }, triggerContext -> {
            CronTrigger trigger = new CronTrigger(corn);
            return trigger.nextExecutionTime(triggerContext);
        });
    }

    public  void sendFilesPost(String url, List<File> fileList,String line) {
        CloseableHttpClient httpClient = HttpClients.createDefault();
        RequestConfig requestConfig = RequestConfig.custom().setConnectTimeout(20000).setSocketTimeout(40000).build();
        HttpPost httpPost = new HttpPost(url);
        httpPost.setConfig(requestConfig);
        String result = null;
        try {

            MultipartEntity reqEntity = new MultipartEntity();
            reqEntity.addPart("line", new StringBody(line));
            for(int i=0;i<fileList.size();i++) {
                FileBody file = new FileBody(fileList.get(i));
                reqEntity.addPart("file"+i, file);// 此处的file为表格里对应的inputtype格式
            }
            httpPost.setEntity(reqEntity);
            HttpResponse response = httpClient.execute(httpPost);
            if (null != response && response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                if (null != resEntity) {
                    result = EntityUtils.toString(resEntity, HTTP.UTF_8);
                    log.info("上传机器文件结果:{}",result);
                    fileCut(fileList);
                }
            }
        }  catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭连接，释放资源
            try {
                httpClient.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    private void fileCut(List<File> fileList) {
        //将文件剪切到另一个目录
        //D://bak
        // /dwq.txt
        String bakDir = basedir.substring(0,basedir.lastIndexOf("/")+1)+"back";
        for (int i = 0; i < fileList.size(); i++) {
            File file = fileList.get(i);
            String filePath = file.getPath().replaceAll("\\\\","/");
            String newFilePath = bakDir+filePath.replace(basedir,"");

            String newFileDirPath = newFilePath.substring(0,newFilePath.lastIndexOf("/"));
            File newFileDir = new File(newFileDirPath);
            if (!newFileDir.exists()){
                newFileDir.mkdirs();
            }

            copyFile(file,newFilePath);
//            File parentFile = new File(file.getParent());
            file.delete();
//            if (parentFile.listFiles().length == 0 && "aoi".equals(machineType)) {
//                parentFile.delete();
//            }
        }
    }

    private void copyFile(File source, String dest)  {
        FileChannel input = null ;
        FileChannel output = null;
        try {
            input = new FileInputStream(source).getChannel();
            output = new FileOutputStream(new File(dest)).getChannel();
            output.transferFrom(input, 0, input.size());
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (input != null) {
                    input.close();
                }
                if (output != null) {
                    output.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }

        }
    }

    public static List<List<File>> groupList(int toIndex, List<File> list) {
        List<List<File>> listGroup = new ArrayList<>();
        int listSize = list.size();
        for (int i = 0; i < list.size(); i += toIndex) {
            if (i + toIndex > listSize) {
                toIndex = listSize - i;
            }
            List<File> newList = list.subList(i, i + toIndex);
            listGroup.add(newList);
        }
        return listGroup;
    }
}
